package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.cucc.client.api.customerOrderInformation.ISerialNumberService;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.ztesoft.bss.common.bo.UserInfo;
import com.ztesoft.bss.common.exception.BssException;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.iwhalecloud.bss.kite.client.dto.cust.ContextCustDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalQuerySeqHelper;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;

import com.ztesoft.bss.common.util.ContextUtil;

/**
 * <Description> 业务号码 <br>
 *
 * @version 1.0<br>
 * @see com.iwhalecloud.bss.kite.web.service.accept.attr.handler <br>
 * @since R9.0<br>
 */
@Service
public class LocalGenNumberCommonAttrHandler extends AbstractAttrHandler {
    @Autowired
    private OperateInstAttrService operateInstAttrService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private ISerialNumberService serialNumberService;

    @Override
    public void init(CommonAttrVO commonAttr) {
        // 判断追加订购业务,第一次初始化的时候新生成号码,后面每次初始化不生成新号码
        KiteSceneInst kiteSceneInst = querySceneInstService
            .getSceneInst(KiteWebContext.getContext().getCurrentSceneInstId());
        String flag = querySceneInstService
            .getExtParameterValue(kiteSceneInst.getSceneInstId(), LocalKeyConsts.ADD_ORDE_RGE_NNUM);

        String orderNatureValue = querySceneInstService.getCommonAttrValue(kiteSceneInst.getSceneInstId(), LocalKeyConsts.ORDER_NATURE);
        if(!KiteStringUtils.isEqual(orderNatureValue, "2")) {
            commonAttr.setIsEdit(KeyConsts.IFTRUE_F);
            KiteAttr serialNumberAttr = querySceneInstService.getCommonAttr(kiteSceneInst.getSceneInstId(), "business_number");
            serialNumberAttr.setIsEdit(KeyConsts.IFTRUE_F);
            operateSceneInstService.setCommonAttr(kiteSceneInst.getSceneInstId(), serialNumberAttr);
        }

        if (!KiteStringUtils.isEmpty(commonAttr.getOriginValue()) && commonAttr.getOriginValue()
            .equals(commonAttr.getValue()) && !KiteStringUtils.isEqual(KeyConsts.IFTRUE_T, flag)) {
            return;
        }
        // 云业务订购时不生成号码
        String rootInstId = kiteSceneInst.getRootInstId();
        String custId = KiteWebContext.getContext().getCust().getCustId();
        String cateId = querySceneInstService.getOfferInstAttrValue(custId, rootInstId, "cateId");
        if (KiteStringUtils.equalsAny(cateId, "2000998", "2100982", "2100983") && (KiteStringUtils.isEmpty(commonAttr.getValue()) || KiteStringUtils.isEqual(KeyConsts.IFTRUE_T, flag))) {
            return;
        }

        if (KiteStringUtils.isEmpty(commonAttr.getValue()) || KiteStringUtils.isEqual(KeyConsts.IFTRUE_T, flag)) {
            String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
            // 序列
            Map<String, String> inParam = new HashMap<>();
            ContextCustDTO oldCustDTO = KiteWebContext.getContext().getCust();
            CuccContextCustDTO custDTO = KiteBeanUtils.transform(oldCustDTO, CuccContextCustDTO.class);
            if (KiteStringUtils.isEmpty(custDTO.getEparchyCode())) {
                custDTO.setEparchyCode(ContextUtil.getLoginInfo().getUserInfo().getPostLanId());
            }
            inParam.put("SEQ_TYPE", "SERIAL_NUMBER");
            inParam.put("SYS_TYPE", "1");
            inParam.put("SYS_SOURCE", "");
            String seq = LocalQuerySeqHelper.getSeqBySeqType(inParam, sceneInstId, custDTO);
            if (KiteStringUtils.isEmpty(seq)) {
                seq = LocalKeyConsts.EMPTY_SERIAL_NUMBER;
            } else {
                commonAttr.setOriginValue(seq);
            }
            commonAttr.setValue(seq);
            commonAttr.setValueDesc(seq);
            setCommonAttr(commonAttr);

            List<KiteProdInst> kiteProdInsts = querySceneInstService.listProdInsts(sceneInstId);
            String finalSeq = seq;
            kiteProdInsts.stream().forEach(kiteProdInst -> {
                KiteAttr attr = kiteProdInst.getAttr("200004128");
                if(!ObjectUtils.isEmpty(attr)){
                    Map<String, String> param = new HashMap<>();
                    param.put("SEQ_TYPE", "WLW_COMMUNICATE_ID");
                    param.put("SYS_TYPE", "1");
                    param.put("SYS_SOURCE", "");
                    String str = LocalQuerySeqHelper.getSeqBySeqType(param, sceneInstId, custDTO);
                    str = finalSeq + "_TX_" + str;
                    attr.setValue(str);
                    operateInstAttrService.setAttrValue(kiteProdInst, "200004128", str, sceneInstId, null);
                }
            });
            operateSceneInstService.putExtParameter(sceneInstId, LocalKeyConsts.ADD_ORDE_RGE_NNUM, "F");
        }
    }

    /**
     * 业务开通-补录单，手动输入业务号码校验：
     * 1.调用用户中心的接口，校验号码唯一性
     * 2.再调用订单中心的在途单校验
     */
    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        value = KiteStringUtils.trim(value);
        valueDesc = value;
        if(KiteStringUtils.isNotEmpty(value)) {
            KiteAttr kiteAttr = querySceneInstService.getCommonAttr(sceneInstId, fieldName);
            // 判断值=初始值，则跳过校验
            if(!KiteStringUtils.isEqual(value, kiteAttr.getOriginValue())) {
                // 订单性质（2：补录单）
                String orderNature = querySceneInstService.getCommonAttrValue(sceneInstId, LocalKeyConsts.ORDER_NATURE);
                if(KiteStringUtils.isEqual(orderNature, "2") && KiteStringUtils.isEqual(kiteAttr.getIsEdit(), KeyConsts.IFTRUE_T)) {
                    // 手动输入业务号码情况
                    ContextCustDTO custDTO1 = KiteWebContext.getContext().getCust();
                    CuccContextCustDTO cuccContextCustDTO = KiteBeanUtils.transform(custDTO1, CuccContextCustDTO.class);
                    Map<String, String> regionMap = new HashMap<>(8);
                    if (Objects.nonNull(cuccContextCustDTO) && KiteStringUtils.isNotEmpty(cuccContextCustDTO.getProvinceCode())) {
                        regionMap.put("PROVINCE_CODE", cuccContextCustDTO.getProvinceCode());
                        regionMap.put("EPARCHY_CODE", cuccContextCustDTO.getEparchyCode());
                        regionMap.put("AREA_CODE", cuccContextCustDTO.getRegionId());
                    } else {
                        UserInfo userInfo = ContextUtil.getLoginInfo().getUserInfo();
                        regionMap.put("PROVINCE_CODE", userInfo.getPostProvinceNbr());
                        regionMap.put("EPARCHY_CODE", userInfo.getPostLanId());
                        regionMap.put("AREA_CODE", userInfo.getPostLanId());
                    }
                    regionMap.put("SERIAL_NUM", value);
                    List<KiteProdInst> kiteProdInstList = querySceneInstService.listProdInsts(sceneInstId);
                    String roleId = kiteProdInstList.get(0).getRoleId();
                    regionMap.put("SERVICE_ID", roleId);
                    // 业务号码是否可用校验
                    Map<String, String> validMap = serialNumberService.serialNumberValid(regionMap);
                    if(!KiteStringUtils.isEqual(MapUtils.getString(validMap, "code"), "00000")) {
                        BssException.throwOut("", "", "校验业务号码是否可用接口失败：" + MapUtils.getString(validMap, "message"));
                    }
                    if(KiteStringUtils.isEqual(MapUtils.getString(validMap, "rspCode"), "0001")) {
                        BssException.throwOut("", "", "用户中心已经存在该号码信息，请核对后操作");
                    }
                    if(KiteStringUtils.isEqual(MapUtils.getString(validMap, "rspCode"), "0002")) {
                        BssException.throwOut("", "", "您输入的业务号码不允许是本月已销户的号码，请您重新输入或下月再进行业务补录");
                    }

                    String catagoryId = CuccPosServiceUtils.getCateId(sceneInstId, KiteWebContext.getContext().getCustId());
                    Map<String, String> checkReqMap = new HashMap<>(4);
                    checkReqMap.put("SERIAL_NUMBER", value);
                    checkReqMap.put("TYPE", "order");
                    checkReqMap.put("GOODS_CATAGORY_ID", catagoryId);
                    Map<String, Object> checkMap = serialNumberService.checkPassageOrder(checkReqMap);
                    if(!KiteStringUtils.isEqual(MapUtils.getString(checkMap, "code"), "00000")) {
                        BssException.throwOut("", "", "校验业务号码是否有在途单接口失败：" + MapUtils.getString(checkMap, "message"));
                    }
                    if(MapUtils.getBooleanValue(checkMap, "data", true)) {
                        BssException.throwOut("", "", "该业务号码已经存在在途单，请核对后操作");
                    }
                }
            }
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }
}
